package com.gexiaobao.pigeon.ui.fragment.mine.organization.activity

import android.annotation.SuppressLint
import android.os.Bundle
import android.view.inputmethod.EditorInfo
import androidx.core.view.isVisible
import androidx.core.widget.addTextChangedListener
import androidx.recyclerview.widget.LinearLayoutManager
import com.gexiaobao.pigeon.R
import com.gexiaobao.pigeon.app.base.BaseActivity
import com.gexiaobao.pigeon.app.ext.hideSoftKeyboard
import com.gexiaobao.pigeon.app.ext.init
import com.gexiaobao.pigeon.app.ext.showMessage
import com.gexiaobao.pigeon.app.util.RxToast
import com.gexiaobao.pigeon.app.util.SettingUtil
import com.gexiaobao.pigeon.app.util.StatusBarUtil
import com.gexiaobao.pigeon.app.util.Util
import com.gexiaobao.pigeon.app.weight.recycleview.SpaceItemDecoration
import com.gexiaobao.pigeon.databinding.ActivityGatherPigeonBinding
import com.gexiaobao.pigeon.ui.adapter.GatherPigeonAdapter
import com.gexiaobao.pigeon.ui.dialog.RxDialogPageTurning
import com.gexiaobao.pigeon.ui.fragment.mine.organization.video.ActivityPlayBack
import com.gexiaobao.pigeon.viewmodel.TrainingInfoViewModel
import me.hgj.jetpackmvvm.ext.util.setOnclickNoRepeat
import me.hgj.jetpackmvvm.util.startActivity
import kotlin.math.ceil

/**
 * @Author      : hxw
 * @Date        : 2024/7/23 17:14
 * @Describe    : 集鸽详情
 */
class ActivityPigeonGatheringDetail : BaseActivity<TrainingInfoViewModel, ActivityGatherPigeonBinding>() {

    private var mPassId = ""
    private var searchNameStr = ""
    private var mTitle = ""
    private val mAdapter: GatherPigeonAdapter by lazy { GatherPigeonAdapter(arrayListOf()) }
    private var mRaceId: Int = 0
    private var mGatherId: Int = 0
    private var mPageNo: Int = 1
    private var mPageTotal = 0
    private var mTotalNum = 0

    override fun initView(savedInstanceState: Bundle?) {
        StatusBarUtil.setTranslucentForImageView(this, 0, null)
        mTitle = intent.getStringExtra("title").toString()
        if (intent.hasExtra("raceId")) {
            mRaceId = intent.getIntExtra("raceId", 0)
        }
        mDatabind.includeBar.tvTitle.text = mTitle

        mPassId = intent.getIntExtra("passId", 0).toString()
        searchData(mPageNo)

        mDatabind.includeSearch.editQuery.addTextChangedListener {
            mDatabind.includeSearch.ivClose.isVisible = it.toString().isNotEmpty()
        }

        mDatabind.includeSearch.editQuery.setOnEditorActionListener { _, i, _ ->
            when (i) {
                EditorInfo.IME_ACTION_SEARCH -> {
                    mPageNo = 1
                    searchNameStr = mDatabind.includeSearch.editQuery.text.toString()
                    searchData(mPageNo)
                }

                else -> {}
            }
            false
        }

        mDatabind.layoutList.swipeRecyclerView.init(LinearLayoutManager(this), mAdapter)
            .addItemDecoration(SpaceItemDecoration(0, Util.dp2px(this, 0f)))

        mDatabind.layoutList.swipeRefreshLayout.init {
            searchNameStr = mDatabind.includeSearch.editQuery.text.toString()
            mViewModel.getGatherListForHand(mPassId, searchNameStr, mPageNo)
        }

        mAdapter.setOnItemClickListener { _, _, position ->
            mGatherId = mAdapter.data[position].id
            mViewModel.getVisitMemberNoList(mRaceId.toString())
        }

        mAdapter.addChildClickViewIds(R.id.tv_item_sign_up_pigeon_foster_name, R.id.tv_item_sign_up_pigeon_member_num)
        mAdapter.setOnItemChildClickListener { _, view, position ->
            when (view.id) {
                R.id.tv_item_sign_up_pigeon_foster_name -> {
                    mPageNo = 1
                    searchNameStr = mAdapter.data[position].fosterName
                    searchData(mPageNo)
                    mDatabind.includeSearch.editQuery.setText(searchNameStr)
                    mDatabind.includeSearch.editQuery.setSelection(searchNameStr.length)
                }

                R.id.tv_item_sign_up_pigeon_member_num -> {
                    mPageNo = 1
                    searchNameStr = mAdapter.data[position].memberNum
                    searchData(mPageNo)
                    mDatabind.includeSearch.editQuery.setText(searchNameStr)
                    mDatabind.includeSearch.editQuery.setSelection(searchNameStr.length)
                }
            }
        }
    }

    @SuppressLint("SetTextI18n", "NotifyDataSetChanged")
    override fun createObserver() {
        super.createObserver()
        /** 获取单用户下探视棚号列表  */
        mViewModel.visitMemberResult.observe(this) {
            if (it.list.isNotEmpty()) {
                startActivity<ActivityPlayBack>(
                    "gatherId" to mGatherId,
                    "title" to "集鸽视频",
                    "type" to 1,
                )
            } else {
                showMessage(getString(R.string.no_member_and_can_not_look_video))
            }
        }
        /** 集鸽详情 */
        mViewModel.gatherDetailResponse.observe(this) {
            if (mDatabind.layoutList.swipeRefreshLayout.isRefreshing) {
                mDatabind.layoutList.swipeRefreshLayout.isRefreshing = false
            }
            mTotalNum = it.total
            mAdapter.setTotal(mTotalNum, mPageNo)
            mAdapter.setList(it.data)
            mAdapter.notifyDataSetChanged()
            mPageTotal = ceil(SettingUtil.div(mTotalNum.toDouble(), 50.00, 2)).toInt()//取整
            mDatabind.organizeSearchNumber.text =
                getString(R.string.tv_training_sign_pigeon_num) + it.total + getString(R.string.yu) + "    " + getString(R.string.altogether) + mPageTotal + getString(
                    R.string.page
                )
            mDatabind.layoutList.swipeRecyclerView.scrollToPosition(0)
        }
    }

    override fun onBindViewClick() {
        super.onBindViewClick()
        setOnclickNoRepeat(
            mDatabind.includeBar.ivBack,
            mDatabind.includeSearch.tvSearch,
            mDatabind.includeSearch.ivClose,
            mDatabind.includeBottomPage.tvFirstPage,
            mDatabind.includeBottomPage.tvPageUp,
            mDatabind.includeBottomPage.tvLastPage,
            mDatabind.includeBottomPage.tvThrough,
            mDatabind.includeBottomPage.tvNextPage,
        ) {
            when (it) {
                mDatabind.includeBottomPage.tvThrough -> showDialogPageTurning()
                mDatabind.includeBottomPage.tvLastPage -> {
                    mPageNo = mPageTotal
                    searchData(mPageNo)
                    searchNameStr = mDatabind.includeSearch.editQuery.text.toString()
                    mDatabind.includeBottomPage.tvPageNumber.text = mPageNo.toString()
                }

                mDatabind.includeBottomPage.tvNextPage -> {
                    if (mPageNo == mPageTotal) {
                        RxToast.warning(getString(R.string.last_page))
                        return@setOnclickNoRepeat
                    }
                    mPageNo++
                    searchData(mPageNo)
                    searchNameStr = mDatabind.includeSearch.editQuery.text.toString()
                    mDatabind.includeBottomPage.tvPageNumber.text = mPageNo.toString()
                }

                mDatabind.includeBottomPage.tvPageUp -> {
                    if (mPageNo == 1) {
                        RxToast.warning(getString(R.string.first_page))
                        return@setOnclickNoRepeat
                    }
                    mPageNo--
                    searchData(mPageNo)
                    searchNameStr = mDatabind.includeSearch.editQuery.text.toString()
                    mDatabind.includeBottomPage.tvPageNumber.text = mPageNo.toString()
                }

                mDatabind.includeBottomPage.tvFirstPage -> {
                    mPageNo = 1
                    searchData(mPageNo)
                    searchNameStr = mDatabind.includeSearch.editQuery.text.toString()
                    mDatabind.includeBottomPage.tvPageNumber.text = mPageNo.toString()
                }

                mDatabind.includeSearch.ivClose -> {
                    mPageNo = 1
                    mDatabind.includeSearch.editQuery.setText("")
                    searchNameStr = mDatabind.includeSearch.editQuery.text.toString()
                    searchData(mPageNo)
                }

                mDatabind.includeBar.ivBack -> finish()
                mDatabind.includeSearch.tvSearch -> {
                    searchNameStr = mDatabind.includeSearch.editQuery.text.toString()
                    mPageNo = 1
                    searchData(mPageNo)
                }
            }
        }
    }

    private fun showDialogPageTurning() {
        var pageNumber: Int
        val dialog = RxDialogPageTurning(this)
        dialog.setTitle(getString(R.string.chose_look_page) + "\n" + getString(R.string.altogether) + mPageTotal + getString(R.string.page))
        dialog.setPlusListener {
            pageNumber = if (dialog.getCurrentPage().isEmpty()) {
                1
            } else {
                dialog.getCurrentPage().toInt()
            }
            if (pageNumber > mPageTotal) {
                RxToast.warning(getString(R.string.has_exceeded_the_total_page))
                return@setPlusListener
            }
            if (pageNumber == mPageTotal) {
                RxToast.warning(getString(R.string.last_page))
                return@setPlusListener
            }
            pageNumber++
            dialog.setCurrentPage(pageNumber.toString())
        }
        dialog.setMinusListener {
            pageNumber = if (dialog.getCurrentPage().isEmpty()) {
                1
            } else {
                dialog.getCurrentPage().toInt()
            }

            if (pageNumber == 1) {
                RxToast.warning(getString(R.string.first_page))
                return@setMinusListener
            }
            pageNumber--
            dialog.setCurrentPage(pageNumber.toString())
        }
        dialog.setSureListener {
            mPageNo = if (dialog.getCurrentPage().isEmpty()) {
                1
            } else {
                dialog.getCurrentPage().toInt()
            }
            if (mPageNo > mPageTotal) {
                RxToast.warning(getString(R.string.has_exceeded_the_total_page))
                return@setSureListener
            }
            mDatabind.includeBottomPage.tvPageNumber.text = mPageNo.toString()
            searchData(mPageNo)
            dialog.dismiss()
        }
        dialog.setFullScreenWidth()
        dialog.show()
    }

    private fun searchData(pageNo: Int) {
        hideSoftKeyboard(this)
        showLoading(getString(R.string.loading))
        mViewModel.getGatherListForHand(mPassId, searchNameStr, pageNo)
    }
}